package com.tianji.remark.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tianji.common.autoconfigure.mq.RabbitMqHelper;
import com.tianji.common.constants.MqConstants;
import com.tianji.common.domain.dto.LikedTimesDTO;
import com.tianji.common.utils.CollUtils;
import com.tianji.common.utils.UserContext;
import com.tianji.remark.domain.dto.LikeRecordFormDTO;
import com.tianji.remark.domain.po.LikedRecord;
import com.tianji.remark.mapper.LikedRecordMapper;
import com.tianji.remark.service.ILikedRecordService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 点赞记录表 服务实现类
 * </p>
 *
 * @author zpf
 */
//@Service
public class LikedRecordServiceImpl extends ServiceImpl<LikedRecordMapper, LikedRecord> implements ILikedRecordService {
    @Autowired
    private RabbitMqHelper mqHelper;

    @Override
    public Set<Long> isBizLiked(List<Long> bizIds, String bizType) {
        Long userId = UserContext.getUser();
        List<LikedRecord> list = this.lambdaQuery()
                .select(LikedRecord::getBizId)
                .eq(LikedRecord::getUserId, userId)
                .eq(LikedRecord::getBizType, bizType)
                .in(LikedRecord::getBizId, bizIds)
                .list();
        if(CollUtils.isEmpty(list)){
            return new HashSet<>();
        }
        return list.stream().map(LikedRecord::getBizId).collect(Collectors.toSet());
    }

    @Override
    public void addLikeRecord(LikeRecordFormDTO dto) {
        //获取用户id
        Long userId = UserContext.getUser();
        // 判断是否是个点赞
        Boolean liked = dto.getLiked();
        if(liked){
            // 说明是点赞
            // 查询是否点过赞，userId、bizId、bizType
            LikedRecord likedRecord = getUserLikeRecord(userId, dto.getBizId(), dto.getBizType());
            // 如果点过
            if(likedRecord != null){
                return;
            }
            // 如果没点过
            // 新增点赞记录
            LikedRecord record = BeanUtil.copyProperties(dto, LikedRecord.class);
            record.setUserId(userId);
            record.setCreateTime(LocalDateTime.now());
            record.setUpdateTime(LocalDateTime.now());
            this.save(record);
            // 统计点赞数量，发送mq消息
            sendMqMsg(dto.getBizId(), dto.getBizType());
        }else{
            // 说明是取消点赞
            // 查询是否点过赞，userId、bizId、bizType
            LikedRecord likedRecord = getUserLikeRecord(userId, dto.getBizId(), dto.getBizType());
            // 如果没点过赞，return
            if(likedRecord == null){
                return;
            }
            // 如果点过赞
            // 删除点赞记录
            LambdaQueryWrapper<LikedRecord> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(LikedRecord::getUserId, userId)
                    .eq(LikedRecord::getBizId, dto.getBizId())
                    .eq(LikedRecord::getBizType, dto.getBizType());
            this.remove(queryWrapper);
            // 统计点赞数量，发送mq消息
            sendMqMsg(dto.getBizId(), dto.getBizType());
        }
    }

    private void sendMqMsg(Long bizId, String bizType){
        // 统计点赞数量
        Integer count = this.lambdaQuery()
                .eq(LikedRecord::getBizId, bizId)
                .eq(LikedRecord::getBizType,bizType)
                .count();
        // 发送MQ
        LikedTimesDTO likedTimesDTO = new LikedTimesDTO(bizId, count, bizType);
        String key = MqConstants.Key.LIKED_TIMES_KEY_TEMPLATE.replace("{}", bizType);
        mqHelper.send(MqConstants.Exchange.LIKE_RECORD_EXCHANGE, key, likedTimesDTO);
    }
    private LikedRecord getUserLikeRecord(Long userId, Long bizId, String bizType){
        return this.lambdaQuery().eq(LikedRecord::getUserId, userId)
                .eq(LikedRecord::getBizId, bizId)
                .eq(LikedRecord::getBizType, bizType)
                .one();
    }


}